<?php
/**
 * 使用说明  默认控制器  资费说明
 */
class Controller_my extends Controller_Abstract
{
   function _before_execute(){
     
   	    if(!isset($_COOKIE['user_id'])){
	        message('请先登录！','/baodan/login');
	    }else{
	        $user = Acctuser::find('id = ?',$_COOKIE['user_id'])->getOne();
	        if(!$user->id()){
	            message('请先登录！','/baodan/login');
	        }else{
	            $_SESSION['user'] = $user->toArray();
	        }
	    }
   }


   /**
    * 激活码
    */
   
   function actionkeys(){
       $activecode = activecode::find('bdcenter_acctname = ?',$_SESSION['user']['acctname'])->asArray()->getAll();
       $unactive = array();
       $active = array();
       if(count($activecode)){
           foreach ($activecode as $v){
               if($v['used'] == 0){
                   $unactive[] = $v;
               }else{
                   $active[] = $v;
               }
           }
       }
       $status = intval($this->_context->status);
       $this->_view['status'] = $status;
       $this->_view['unactive'] = $unactive;
       $this->_view['active'] = $active;
   }
   /**
    * 分配key
    */
   function actionkeysused(){
       if($this->_context->isGET()){
           $keyword = urldecode($this->_context->keyword);
           $this->_view['keyword']  = $keyword;
           $keyid  = intval($this->_context->keyid);
           $this->_view['keyid']  = $keyid;
           if(empty($keyword)) {
               $user = array();
           }else{
               $user = Acctuser::find('acctname = ? or realname = ?',$keyword,$keyword)->setColumns('id,realname,acctname,active_code')->asArray()->getAll();
           }
           $this->_view['user']  = $user;
       }else{
           $uid = $this->_context->uid;
           $keyid = $this->_context->keyid;
           $user =   Acctuser::find('id = ?',$uid)->getOne();
           
           if(!$user->id()){
               exit(json_encode(array('status'=>1,'msg'=>'用户不存在')));
           }
           if($user->is_active == 1){
               exit(json_encode(array('status'=>2,'msg'=>'该用户已被激活')));
           }
           if($user->active_code != ''){
               exit(json_encode(array('status'=>3,'msg'=>'该用户已经分配了激活码')));
           }
           
           $key = activecode::find('id = ?',$keyid)->getOne();
           if(!$key->id()){
               exit(json_encode(array('status'=>4,'msg'=>'激活码不存在')));
           }
           if($key->used == 1){
               exit(json_encode(array('status'=>5,'msg'=>'激活码已经被使用')));
           }
      
            
            $time = time();
            //用户激活
            $time = time();
            $user->active_code = $key->active_code;
            $user->is_active = 1;
            $user->active_time = $time;
            $user->save();
            //激活码使用
            $key->used_acctname = $user->acctname;
            $key->used_realname = $user->realname;
            $key->used = 1;
            $key->usedtime = $time;
            $key->save();
            $grade_xd = Acctuser::getdainumbyuid($_SESSION['user']['id'], $user);
            //报单记录
            $bdlogdata =  array(
                'bdcenter_acctname'=>$_SESSION['user']['acctname'],
                'bdcenter_realname'=>$_SESSION['user']['realname'],
                'bd_acctname'=>$user->acctname,
                'bd_realname'=>$user->realname,
                'level'=>$grade_xd,
            );
            $bdlog = new bdlog($bdlogdata);
            $bdlog->save();
          //  print_r($key);die;
            //所有用户升级---
            $maxjichalevelkey = 'maxjichalevel'.$user->acctname;
            if(isset($_SESSION[$maxjichalevelkey])) unset($_SESSION[$maxjichalevelkey]);
            Acctuser::rewardandlevelup($user,0);
            if(isset($_SESSION[$maxjichalevelkey])) unset($_SESSION[$maxjichalevelkey]);
            exit(json_encode(array('status'=>0,'msg'=>'激活成功')));
       }
       
   }
   /**
    * 报单记录
    */
   function actionbdlog(){
       if($this->_context->isPOST()){
           $last = $this->_context->last;
           $log = bdlog::find('bdcenter_acctname = ?',$_SESSION['user']['acctname'])->limit($last, 10)->order('id DESC')->asArray()->getAll();
           if(!count($log)){
               exit(json_encode(array('status'=>0,'msg'=>'没有更多记录')));
           } else {
               foreach ($log as $k=>$v){
                  $log[$k]['created'] = date('Y-m-d H:i:s',$v['created']);
               }
               exit(json_encode(array('status' => 0, 'data' => $log)));
           }
       }else{
        
           $log = bdlog::find('bdcenter_acctname = ?',$_SESSION['user']['acctname'])->limit(0,10)->order('id DESC')->asArray()->getAll();
           
           $this->_view['log'] = $log;
       }
       
       
       
       
       
   }
   /**
    * 积分明细
    */
   
   function actionpointlog(){

       if($this->_context->isPOST()){
           $last = $this->_context->last;
           $log = pointlog::find('reward_acctname = ?',$_SESSION['user']['acctname'])->limit($last, 10)->order('id DESC')->asArray()->getAll();
           
           if(!count($log)){
               exit(json_encode(array('status'=>0,'msg'=>'没有更多记录')));
           } else {
               foreach ($log as $k=>$v){
                   $log[$k]['created'] = date('Y-m-d H:i:s',$v['created']);
               }
               exit(json_encode(array('status' => 0, 'data' => $log)));
           }
       }else{
       
           $log = pointlog::find('reward_acctname = ?',$_SESSION['user']['acctname'])->limit(0,10)->order('id DESC')->asArray()->getAll();
           $this->_view['log'] = $log;
       }
        
   }
   /**
    * 我的激活码
    */
   
   function actionactivecode(){
       
       if($this->_context->isGET()){
           $user = Acctuser::find('id = ?',$_SESSION['user']['id'])->getOne();
           if(!$user->id()){
               message('请先登录！','/baodan/login');
           }else{
               $this->_view['user'] = $user;
           }
       }else{}
   }
   /**
    * 我的团队
    */
   function actionteam(){
       $uid = $_SESSION['user']['id'];
       $teamsql = "select id,acctname,realname,active_time,team_tag from acct_user where find_in_set({$uid},team_tag)";
        $team =  QDB::getConn()->execute($teamsql)->fetchAll();
       $user = Acctuser::find('id = ?',$uid)->getOne();
       $num = count($team);
       if($uid == 11)  $num += $user->num;
       
       $this->_view['num'] = $num;
       $this->_view['team'] = $team;
        
   }

   /**
    * 邀请好友
    */
   function actionshare(){

       $user = Acctuser::find('id = ?',$_SESSION['user']['id'])->getOne();
       
       include_once Q::ini ( 'app_config/ROOT_DIR' ) .'/lib/qr/phpqrcode.php';
       $path = Q::ini ( 'app_config/ROOT_DIR' )."/public/baodan/qrcode/";
       $acctname = $user->acctname;
       //检查目录
       $filename = $acctname.'.png';
       $errorCorrectionLevel = 'L';    //容错级别
       $matrixPointSize = 6;           //生成图片大小
       $url =  Helper_Common::getRequestHost().'baodan/register?recacctname='.base64_encode($acctname);
       //生成二维码图片
       QRcode::png($url,$path.$filename,$errorCorrectionLevel,$matrixPointSize);
       $qrcode = Helper_Common::getRequestHost().'baodan/qrcode/'.$acctname.'.png';

       $this->_view['user'] = $user;
       $this->_view['qrcode'] = $qrcode;
       
        
   }
   /**
    * 绑定提现账号
    */
   function actionbindaccount(){

       $user = Acctuser::find('id = ?',$_SESSION['user']['id'])->getOne();
       if($this->_context->isPOST()){
            //微信收款二维码
           $wechatupfiles = (isset($_FILES['wechatqrcode']))?$_FILES['wechatqrcode']:'';
           if(isset($wechatupfiles) && !empty($wechatupfiles['name'] )){
                
               $allowExt = array('jpg','png','jpeg','pjpeg');
               $localName = $wechatupfiles['name'];
               $fileInfo = pathinfo($localName);
               $extension = $fileInfo['extension'];
               if(!in_array(strtolower($extension) , $allowExt)){
                   exit("文件后缀错误");
               }
               $path = Q::ini ( 'app_config/ROOT_DIR' ) . '/public/baodan/wechatqrcode';
                
               if (! is_dir ( $path )) {
                   @mkdir ( $path, 0700 );
               }
               $time = date('YmdHis');
               $filename =  $user->id.'_'.$time.'.jpg';
               move_uploaded_file($wechatupfiles["tmp_name"],$path.'/'.$filename);
               $filepath = $path.'/'.$filename;
       
               $host = Helper_Common::getRequestHost ();
               if($user->wechat_qrcode){
                   $oldpath1 = str_replace($host, '', $user->wechat_qrcode);
               }
               $wechatqrcode = $host . '/baodan/wechatqrcode/' . $filename;
               $user->wechat_qrcode = $wechatqrcode;
               $user->save();
               if(!empty($oldpath1)){//新图片上传成功之后才删除旧图片 避免被占用过多的空间
                   global $root_dir;
                   $oldimgpath1=$root_dir . '/' . 'public'. '/'.$oldpath1;
                   Helper_Common::safeDelFile($oldimgpath1);
               }
               
           }
           //支付宝收款二维码
           $alipayupfiles = (isset($_FILES['alipayqrcode']))?$_FILES['alipayqrcode']:'';
          
           if(isset($alipayupfiles) && !empty($alipayupfiles['name']) ){
           
               $allowExt = array('jpg','png','jpeg','pjpeg');
               $localName = $alipayupfiles['name'];
               $fileInfo = pathinfo($localName);
               $extension = $fileInfo['extension'];
               if(!in_array(strtolower($extension) , $allowExt)){
                   exit("文件后缀错误");
               }
               $path = Q::ini ( 'app_config/ROOT_DIR' ) . '/public/baodan/alipayqrcode';
           
               if (! is_dir ( $path )) {
                   @mkdir ( $path, 0700 );
               }
               $time = date('YmdHis');
               $filename =  $user->id.'_'.$time.'.jpg';
               move_uploaded_file($alipayupfiles["tmp_name"],$path.'/'.$filename);
               $filepath = $path.'/'.$filename;
                
               $host = Helper_Common::getRequestHost ();
               if($user->alipay_qrcode){
                   $oldpath1 = str_replace($host, '', $user->alipay_qrcode);
               }
               $alipayqrcode = $host . 'baodan/alipayqrcode/' . $filename;
               $user->alipay_qrcode = $alipayqrcode;
               $user->save();
               if(!empty($oldpath2)){//新图片上传成功之后才删除旧图片 避免被占用过多的空间
                   global $root_dir;
                   $oldimgpath2=$root_dir . '/' . 'public'. '/'.$oldpath1;
                   Helper_Common::safeDelFile($oldimgpath2);
               }
                
           }
          
           header('location: /my/bindaccount');die;
        
           
       }else{  
           $this->_view['user'] = $user;
       }

       
   }
   

   /**
    * 提现
    */
   function actionwithdraw(){
       $user = Acctuser::find('id = ?',$_SESSION['user']['id'])->getOne();
       if($this->_context->isPOST()){
           $paymethod = ($this->_context->paymethod);
           $balance = ($this->_context->balance);
           $min_withdraw = Helper_Common::getPublicSet('min_withdraw', 1);
           $balance = abs(sprintf('%.2f',$balance));
           if($balance <$min_withdraw  ){
               exit(json_encode(array('status'=>1,'msg'=>'最低'.$min_withdraw.'起提')));
             
           }
           if($balance > $user->balance  ){
               exit(json_encode(array('status'=>5,'msg'=>'超过最大可提现额度')));
                
           }
           if($paymethod !='wechat' && $paymethod !='alipay'){
 
             exit(json_encode(array('status'=>2,'msg'=>'请选择支付方式')));
              
           }else{
               if($paymethod == 'wechat' && !$user->wechat_qrcode){
                   exit(json_encode(array('status'=>3,'msg'=>'请先上传微信收款截图')));
               }
               if($paymethod == 'alipay' && !$user->alipay_qrcode){
                   exit(json_encode(array('status'=>4,'msg'=>'请先上传支付宝收款截图')));
               }
                $data = array(
                    'balance'=>$balance,
                    'user_id'=>$_SESSION['user']['id'],
                    'realname'=>$_SESSION['user']['realname'],
                    'acctname'=>$_SESSION['user']['acctname'],
                    'paymethod'=>$paymethod=='wechat'?'微信':'支付宝',
                    'qrcode'=>$paymethod =='wechat'?$user->wechat_qrcode:$user->alipay_qrcode
                );
                $withdraw = new withdraw($data);
                $withdraw->save();
                
                $user->balance -= $balance;
                $user->save();
                
                
                exit(json_encode(array('status'=>0,'msg'=>'提现申请成功！')));
           }
       }else{
         
           $this->_view['user'] = $user;
       }
    
   }
 
   
   function  actionwithdrawlog() {
       $activecode = withdraw::find('acctname = ?',$_SESSION['user']['acctname'])->asArray()->getAll();
      // print_r($activecode);die;
       $unactive = array();
       $active = array();
       $inactive = array();
       if(count($activecode)){
           foreach ($activecode as $v){
               if($v['status'] == 0){
                   $unactive[] = $v;
               }else if($v['status'] == 2){
                   $inactive[] = $v;
               }else{
                   $active[] = $v;
               }
           }
       }
       $status = intval($this->_context->status);
       $this->_view['status'] = $status;
       $this->_view['unactive'] = $unactive;
       $this->_view['active'] = $active;
       $this->_view['inactive'] = $inactive;
   }
   
   
   
}